package saver

import (
	"fmt"
	"github.com/jmoiron/sqlx"
	"my-crawler/concurrence/task/gzh_comments_num/models"
	"my-crawler/database/mysql"
	"time"
)

func Saver() chan interface{} {
	//任务开始时先创建这个通道
	//这里不仅可以初始化一些其他事情 例如初始化数据库 减少连接
	out := make(chan interface{}, 1)
	client := mysql.Db
	go func() {
		itemCount := 0
		for {
			item := <-out //接收 engine发过来的item
			fmt.Println(item)
			itemCount++
			UpdateInMysql(client, item)
		}
	}()
	return out
}

func UpdateInMysql(db *sqlx.DB, item interface{}) {
	fmt.Println("item")
	fmt.Println(item)
	i := item.(models.Result)
	tt := time.Now().Format("2006-01-02 15:04:05")
	res, err := db.Exec("update  crawler_articles  set comments_sum=? ,updated_at = ? where id=?",
		i.TotalNums, tt, i.ID)
	if err != nil {
		fmt.Println("exec failed, ", err)
		return
	}
	row, err := res.RowsAffected()
	if err != nil {
		fmt.Println("rows failed, ", err)
	}
	fmt.Println("update succ:", row)
}
